import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart' ;
import 'package:flutter/rendering.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart' as Re;
import 'package:ysy_flutter_mvvm_yuanxuan/base/PageProvideNode.dart';
import 'package:ysy_flutter_mvvm_yuanxuan/bean/home/HomeCategoryTabBean.dart';
import 'package:ysy_flutter_mvvm_yuanxuan/bean/home/RecommendCategoryBean.dart';
import 'package:ysy_flutter_mvvm_yuanxuan/bean/home/RecommendGoodsBean.dart';
import 'package:ysy_flutter_mvvm_yuanxuan/helper/RouteHelper.dart';
import 'package:ysy_flutter_mvvm_yuanxuan/helper/SmartRefresherHelper.dart';
import 'package:ysy_flutter_mvvm_yuanxuan/helper/ViewHelper.dart';
import 'package:ysy_flutter_mvvm_yuanxuan/view/main/home/Home.dart';
import '../../../bean/home/HomeContentBean.dart';
import 'package:ysy_flutter_mvvm_yuanxuan/helper/Constant.dart';
import 'package:ysy_flutter_mvvm_yuanxuan/helper/ImageHelper.dart';
import 'package:ysy_flutter_mvvm_yuanxuan/view/main/home/HomeVM.dart';

import 'GoodsTag.dart';
import 'HomeBannerWidget.dart';


var vm = HomeVM();

class AutoRecommend extends StatefulWidget {
  @override
  _AutoRecommendState createState() => _AutoRecommendState();
}

class _AutoRecommendState extends State<AutoRecommend> with AutomaticKeepAliveClientMixin {

  var mRecommend;

  @override
  void initState() {
    super.initState();
    mRecommend=Recommend();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return mRecommend;
  }

  @override
  bool get wantKeepAlive => true;

}

class Recommend extends PageProvideNode  {

  Recommend() : super(vm);

  @override
  Widget buildContent(BuildContext context) {
    HomeVM vm = mProvider as HomeVM;
    WidgetsBinding.instance!.addPostFrameCallback((_) {
      vm.getRecommend();
    });
    return RecommendWidget(vm);
  }
}

//推荐
class RecommendWidget extends StatefulWidget {
  HomeVM mProvider;

  RecommendWidget(this.mProvider);

  @override
  _RecommendWidgetState createState() => _RecommendWidgetState();
}

class _RecommendWidgetState extends State<RecommendWidget> with TickerProviderStateMixin {

  late TabController _dufController = TabController(initialIndex:0,length: 1,vsync: this);
  late PageController _pageController = PageController(initialPage:0,keepPage:true);
  late ScrollController _scrollController=ScrollController();
  ValueNotifier<Color> _tabColorNotifier =ValueNotifier<Color>(Color(ConstantColors.mainBackgroundColor));
  GlobalObjectKey _tabKey=GlobalObjectKey("home_tab");
  late double tabDy;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
       vm.getRecommendCategory();
       RenderBox findRender = _tabKey.currentContext?.findRenderObject() as RenderBox;
       var localToGlobal = findRender.localToGlobal(Offset.zero);
       tabDy=localToGlobal.dy-findRender.size.height-ScreenUtil().statusBarHeight;
    });
    //滑动 监听
    _scrollController..addListener(() {
      double offset = _scrollController.offset;
      // 判断是否滑动超过指定值 来更新 头部背景
      if(offset >42.h ){
        if(homeStateNotifier.value.isTop){
          homeStateNotifier.value.isTop=false;
          homeStateNotifier.notifyListeners();
        };
      }else{
        if(!homeStateNotifier.value.isTop){
          homeStateNotifier.value.isTop=true;
          homeStateNotifier.notifyListeners();
        };
      }
      //// 判断是否滑动超过tabDy 来更新 tab背景
      if(offset >tabDy ){
        if(vm.recommendCategoryTab?.isTabTop!=true){
          vm.recommendCategoryTab?.isTabTop=true;
          _tabColorNotifier.value=Colors.white;
          _tabColorNotifier.notifyListeners();
        };
      }else{
        if(vm.recommendCategoryTab?.isTabTop==true){
          vm.recommendCategoryTab?.isTabTop=false;
          _tabColorNotifier.value=Color(ConstantColors.mainBackgroundColor);
          _tabColorNotifier.notifyListeners();
        };
      }
    });
  }

  @override
  void setState(VoidCallback fn) {
    super.setState(fn);
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (BuildContext context){ return vm;},
      child: Selector(
        selector: (context,HomeVM vm){
          return vm.recommendCategoryTab;
        },
        builder: (context, RecommendCategoryTabBean? value, _){
        _dufController = TabController(initialIndex:0,length: value?.recommendCategoryBeans?.length??1,vsync: this);
          return RefreshIndicator(
            onRefresh: (){
              vm.getRecommend(isDialog: false);
              vm.getRecommendCategory();
              return Future.delayed(Duration(seconds: 1));
              },
              notificationPredicate: (otification){
              return true;
           },
            child: NestedScrollView(
              controller: _scrollController,
                physics: AlwaysScrollableScrollPhysics(),
              headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
                return [
                  SliverToBoxAdapter(
                    child: _Head(widget.mProvider),
                  ),
                  SliverPersistentHeader(
                    floating: true,
                    delegate: StickyTabBarDelegate(
                        color: value?.isTabTop==true?0xffffffff:ConstantColors.mainBackgroundColor,
                        valueNotifier: _tabColorNotifier,
                        child: TabBar(
                            key: _tabKey,
                            isScrollable: true,
                            indicatorColor: Color(ConstantColors.mainColor),
                            indicatorSize: TabBarIndicatorSize.label,
                            indicatorPadding: EdgeInsets.fromLTRB(0, 2.h, 0, 1.h),
                            controller: _dufController,
                            onTap: (page){_pageController.animateToPage(page, duration: Duration(milliseconds: 200), curve: Curves.easeInOut);},
                            tabs: value?.recommendCategoryBeans?.map((e) => Tab(child: Text("${e.name}",style: TextStyle(color: Colors.black,fontSize: 17.sp),),
                            )).toList()??[Tab(child: Text("${""}",style: TextStyle(color: Colors.black,fontSize: 17.sp),),)]
                        )),
                    pinned: true,
                  ),
                ];
              },
              body: Container(
                color: Color(ConstantColors.mainBackgroundColor),
                // child: TabBarView(
                // controller: _dufController, children: value?.recommendCategoryBeans?.map((e) => MGrid(e))?.toList()??[Text("没有数据")]),
                child: PageView.builder(controller:_pageController,
                    physics: PageScrollPhysics(),
                    itemCount: value?.recommendCategoryBeans?.length??0,
                    onPageChanged: (page){_dufController.animateTo(page);},
                    itemBuilder: (BuildContext context, int index){
                      RecommendCategory? e = value?.recommendCategoryBeans?[index];
                      return e==null?Text(""):MGrid(e);
                    }),
              )
               )
          );},
      ),
    );
  }

  @override
  void dispose() {
    _dufController.dispose();
    _scrollController.dispose();
    _pageController.dispose();
    super.dispose();
  }
}

class _Head extends StatefulWidget {
  HomeVM mProvider;

  _Head(this.mProvider, {Key? key}) : super(key: key);

  @override
  _HeadState createState() => _HeadState();
}

class _HeadState extends State<_Head> {
  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        //搜索栏
        SearchWidget(widget.mProvider),
        //轮播图
        Container(
          margin: EdgeInsets.fromLTRB(12.w, 6.h, 12.w, 0),
          height: 160.w,
          decoration: BoxDecoration(borderRadius: BorderRadius.all(Radius.circular(8.0.r))),
          child: MBannerWidget(),
        ),
        //热销排行 //新品首发
        _HotAndNew(),
        SizedBox.fromSize(size: Size(1.h, 14.h),)
      ],
    );
  }
}

//搜索栏
class SearchWidget extends StatefulWidget {
  HomeVM mProvider;

  @override
  _SearchWidgetState createState() => _SearchWidgetState();

  SearchWidget(this.mProvider);
}

class _SearchWidgetState extends State<SearchWidget> {
  @override
  Widget build(BuildContext context) {
    return Container(
        margin: EdgeInsets.fromLTRB(12.w, 2.h, 12.w, 2.h),
        child: Row(
          children: [
            //扫一扫
            Container(
              width: 33.w,
              height: 35.w,
              alignment: Alignment.center,
              margin: EdgeInsets.fromLTRB(0.w, 0, 10.w, 0),
              child: TextButton(
                style: ButtonStyle(
                    minimumSize: MaterialStateProperty.all(Size(0, 0)),
                    padding: MaterialStateProperty.all(EdgeInsets.fromLTRB(0, 0, 0.w, 0))),
                onPressed: () {},
                child: Column(
                  children: [
                    Image.asset(assetPath("ic_home_btn_scan.png"),
                      width: 20.w,
                      height: 20.w,
                    ),
                    Padding(
                      padding: const EdgeInsets.fromLTRB(0, 3, 0, 0),
                      child: Text("扫一扫", style:TextStyle(fontSize: 9.sp,color: Colors.white ),textAlign: TextAlign.end,),
                    )
                  ],
                ),
              ),
            ),
            //搜索框
            Expanded(
              child: TextButton(
                onPressed: () {},
                child: Padding(
                  padding: EdgeInsets.fromLTRB(4.w, 0, 4.w, 0),
                  child: Row(
                    children: [
                      Expanded(child: Text("搜索产品", style: TextStyle(fontSize: 14.sp, color: Color(0xffBFC1CD),),),),
                      Image.asset(assetPath("ic_search_btn_gray.png"), width: 14.w, height: 14.h,)
                    ],
                  ),
                ),
                style: ButtonStyle(
                    backgroundColor: MaterialStateProperty.all(Colors.white),
                    shape: MaterialStateProperty.all(RoundedRectangleBorder(borderRadius: BorderRadius.horizontal(left: Radius.circular(24.r), right: Radius.circular(24.r))))),
              ),
            ),
            //图搜布
            Container(
              width: 33.w,
              height: 35.w,
              alignment: Alignment.center,
              margin: EdgeInsets.fromLTRB(10.w, 0, 0.w, 0),
              child: TextButton(
                style: ButtonStyle(
                    minimumSize: MaterialStateProperty.all(Size(0, 0)),
                    padding: MaterialStateProperty.all(EdgeInsets.fromLTRB(0, 0, 0.w, 0))),
                onPressed: () {},
                child: Column(
                  children: [
                    Image.asset(assetPath("ic_photo_white.png"),
                      width: 20.w,
                      height: 20.w,
                    ),
                    Padding(
                      padding: const EdgeInsets.fromLTRB(0, 3, 0, 0),
                      child: Text("图搜布", style:TextStyle(fontSize: 9.sp,color: Colors.white ),textAlign: TextAlign.end,),
                    )
                  ],
                ),
              ),
            ),
          ],
        ));
  }
}

//热销排行和新品
class _HotAndNew extends StatefulWidget {
  @override
  _HotAndNewState createState() => _HotAndNewState();
}

class _HotAndNewState extends State<_HotAndNew> {
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (_) {
        return vm;
      },
      child: Container(
        decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.all(Radius.circular(8.r))),
        margin: EdgeInsets.fromLTRB(12.w, 16.h, 12.w, 0.h),
        padding: EdgeInsets.fromLTRB(12.w, 14.h, 12.w, 4.h),
        child: Column(
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.end,
              children: [
                Text("热销排行",
                  style: TextStyle(
                      fontSize: 16.sp,
                      color: Color(0xff333333),
                      fontWeight: FontWeight.w700),
                ),
                Container(
                  width: 5.w,
                ),
                Text(
                  "爆款不等人",
                  style: TextStyle(fontSize: 12.sp, color: Color(0xff999999)),
                ),
              ],
            ),
            Container(
              height: ((MediaQuery.of(context).size.width-24.w-6.w*2)/3+58.h),
              margin: EdgeInsets.fromLTRB(0, 10.h, 0, 0),
              child: Selector(
                selector: (context,HomeVM vm){
                return vm.homeBean?.hotProductList;
                },
                builder: (context, List<HotProductList>? list, child){
                  if(list==null || list.isEmpty){
                    return Container(
                      width: double.infinity,
                      alignment: Alignment.center,
                      height: 30.h,
                      child: Text("暂无数据"),
                    );
                  }
                  return  ListView.separated(
                    separatorBuilder: (BuildContext context, int index) {
                      return Container(width: 6.w);
                    },
                    scrollDirection: Axis.horizontal,
                    itemCount: list.length,
                    itemBuilder: (BuildContext context, int index) {
                      HotProductList? item=list[index];
                    return _HotItem(item);
                  });
                }
              ),
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.end,
              children: [
                Text(
                  "新品首发",
                  style: TextStyle(
                      fontSize: 16.sp,
                      color: Color(0xff333333),
                      fontWeight: FontWeight.w700),
                ),
                Container(
                  width: 5.w,
                ),
                Text("行业风向标", style: TextStyle(fontSize: 12.sp, color: Color(0xff999999)),),
              ],
            ),
            Container(
              height: (MediaQuery.of(context).size.width-48.w-8.w*3)/4+36.h,
              margin: EdgeInsets.fromLTRB(0, 10.h, 0, 0),
              child:  Selector(
                selector: (context,HomeVM vm){
                   return vm.homeBean?.newProductList;
                },
                builder: (context, List<NewProductList>? list, child) {
                  if(list==null || list.isEmpty){
                     return Container(
                        width: double.infinity,
                        alignment: Alignment.center,
                        height: 30.h,
                        child: Text("暂无数据"),
                     );
                  }
                  return ListView.separated(
                    separatorBuilder: (BuildContext context, int index) {
                      return Container(width: 8.w);
                    },
                    scrollDirection: Axis.horizontal,
                    itemCount: list.length,
                    itemBuilder: (BuildContext context, int index) {
                      return _NewItem(list[index]);
                    },);
                },)
            )
          ],
        ),
      ),
    );
  }
}

//热销排行 item
class _HotItem extends StatefulWidget {

  HotProductList _item;
  _HotItem(this._item);

  @override
  __HotItemState createState() => __HotItemState();
}

class __HotItemState extends State<_HotItem> {
  @override
  Widget build(BuildContext context) {
    return Container(
      width: (MediaQuery.of(context).size.width-48.w-6.w*2)/3,
      child: Column(
        children: [
          ClipRRect(
            borderRadius: BorderRadius.circular(4.r),
            child: AspectRatio(
              aspectRatio:1/1,
              child: assetImage(
                widget._item.pic??"",
                width: double.infinity,
                fit: BoxFit.fill,
              ),
            ),
          ),
          Container(
            alignment: Alignment.topLeft,
            padding: EdgeInsets.fromLTRB(0, 12.h, 0, 0),
            child: Text(
              widget._item.name??"",
              style: TextStyle(fontSize: 13.sp, color: Color(0xff080A0F)),
              overflow: TextOverflow.ellipsis,
              textAlign: TextAlign.left,
              maxLines: 1,
            ),
          ),
          Container(
            child: Text.rich(
              TextSpan(children: [
                TextSpan(text:"¥ ",style: TextStyle(fontSize: 13.sp, color: Color(ConstantColors.mainTextColor)) ),
                TextSpan(text:"${widget._item.price}",style: TextStyle(fontSize: 16.sp, color: Color(ConstantColors.mainTextColor)) )
              ]),
              textAlign:TextAlign.end,
            ),
            alignment: Alignment.bottomLeft,
            padding: EdgeInsets.fromLTRB(0, 7.h, 0, 0),
          ),
        ],
      ),
    );
  }
}

//新品首发
class _NewItem extends StatefulWidget {
  NewProductList _item;
  _NewItem(this._item);

  @override
  __NewItemState createState() => __NewItemState();
}

class __NewItemState extends State<_NewItem> {
  @override
  Widget build(BuildContext context) {
    return Container(
      width: (MediaQuery.of(context).size.width-48.w-8.w*3)/4,
      child: Column(
        children: [
          ClipRRect(
            borderRadius: BorderRadius.all(Radius.circular(4.r)),
            child: assetImage(
              widget._item.pic??"",
            ),
          ),
          Container(
            alignment: Alignment.bottomCenter,
            padding: EdgeInsets.fromLTRB(0, 10.h, 0, 0),
            child: Row(children: [
              Text("¥",style: TextStyle(fontSize: 13.sp, color: Color(ConstantColors.mainTextColor))),
              Text("${widget._item.price}",style: TextStyle(fontSize: 13.sp, color: Color(ConstantColors.mainTextColor))),
            ],),
          ),
        ],
      ),
    );
  }
}

// 悬浮部分
class StickyTabBarDelegate extends SliverPersistentHeaderDelegate {
  final TabBar child;
  int color;
  ValueNotifier<Color> valueNotifier;

  StickyTabBarDelegate({required this.child,required this.valueNotifier,required this.color});

  @override
  Widget build(
      BuildContext context, double shrinkOffset, bool overlapsContent) {
    return Stack(
      children:[
        ValueListenableBuilder<Color>(
          valueListenable: valueNotifier,
          builder: (BuildContext context, Color value, Widget? child) {
            return Container(color:value ,);
          }
        ),
        Container(
            padding: EdgeInsets.fromLTRB(12.w, 2.h, 12.w, 2.h),
            child: this.child)
      ],
    );
  }

  @override
  double get maxExtent => this.child.preferredSize.height;

  @override
  double get minExtent => this.child.preferredSize.height;

  @override
  bool shouldRebuild(SliverPersistentHeaderDelegate oldDelegate) {
    return true;
  }
}

class MGrid extends PageProvideNode{

  RecommendCategory recommendCategory;

  MGrid(this.recommendCategory ) : super(HomeVM());


  @override
  Widget buildContent(BuildContext context) {
     return _Grid(recommendCategory, mProvider as HomeVM);
  }
}

class _Grid extends StatefulWidget {

  RecommendCategory recommendCategory;

  HomeVM? mHomeVM;

  _Grid(this.recommendCategory, this.mHomeVM);

  @override
  __GridState createState() => __GridState();
}

class __GridState extends State<_Grid> with AutomaticKeepAliveClientMixin {

  Re.RefreshController mRefreshController=Re.RefreshController();
  PullDataRefresher<RecommendGoods> valueNotifier=PullDataRefresher(null);
  late LoadCallback mLoadCallback;

  @override
  void initState() {
    super.initState();
    mLoadCallback=(pullBean){
      widget.mHomeVM?.getRecommendGoods(pullBean,widget.recommendCategory.id,requestDone: (){
        valueNotifier.onRefresher(widget.mHomeVM?.recommendGoodsBeans);
      });
    };
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    var size = MediaQuery.of(context).size;
    return Container(
      padding: EdgeInsets.fromLTRB(12.w, 0, 12.w, 0),
      child: SmartRefresherWidget(
        enablePullDown: false,
        enablePullUp: true,
        controller: mRefreshController,
        valueNotifier: valueNotifier,
        onLoading: mLoadCallback,
        onRefresh: mLoadCallback,
        loadBuild: (context,List<RecommendGoods> list){
           return GridView.builder(
             padding: EdgeInsets.zero,
             gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                 mainAxisSpacing: 1.w, crossAxisSpacing: 8.w, crossAxisCount: 2, mainAxisExtent: (size.width-32.w)/2+96.h ),
             itemCount:list.length,
             itemBuilder: (BuildContext context, int index) {
               return _GridItem(index,list[index]);
             },
           );
        },
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}

// class _Grid extends RefresherWidget<RecommendGoods>{
//
//   RecommendCategory recommendCategory;
//   HomeVM? mHomeVM;
//   ValueNotifier<BaseListDataBean<RecommendGoods>> valueNotifier;
//   _Grid(this.recommendCategory, this.mHomeVM,this.valueNotifier): super(valueNotifier,loading: (PullPageBean bean){
//       mHomeVM?.getRecommendGoods(bean,recommendCategory.id,requestDone: (){
//         if(mHomeVM!=null && mHomeVM.recommendGoodsBeans!=null){
//           valueNotifier.value=mHomeVM.recommendGoodsBeans!;
//           valueNotifier.notifyListeners();
//         }
//       });
//   });
//
//   @override
//   Widget buildContext(BuildContext context, ScrollController mRefreshController, List<RecommendGoods>? result) {
//     var size = MediaQuery.of(context).size;
//     return Container(
//       padding: EdgeInsets.fromLTRB(12.w, 0, 12.w, 0),
//       child: GridView.builder(
//         padding: EdgeInsets.zero,
//         controller: mRefreshController,
//         gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
//             mainAxisSpacing: 1.w, crossAxisSpacing: 8.w, crossAxisCount: 2, mainAxisExtent: (size.width-32.w)/2+92.h ),
//         itemCount:  result?.length??0,
//         physics: NeverScrollableScrollPhysics(),
//         itemBuilder: (BuildContext context, int index) {
//           return _GridItem(index,result?[index]);
//         },
//       ),
//     );
//   }
//
// }

class _GridItem extends StatefulWidget {

  int index;
  RecommendGoods? recommendGood;

  @override
  __GridItemState createState() => __GridItemState();

  _GridItem(this.index, this.recommendGood);
}

class __GridItemState extends State<_GridItem> {

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: (){
        print("object onTap 跳转");
        toGoodsDetails(context,widget.recommendGood?.productId??"");
      },
      child: Container(
        margin: EdgeInsets.fromLTRB(0, 0, 0, 10.h),
        decoration:BoxDecoration(borderRadius: BorderRadius.circular(4.r),color: Colors.white),
        child: Column(
          children: [
            ClipRRect(
              borderRadius: BorderRadius.circular(4.r),
              child: AspectRatio(
                aspectRatio:1/1,
                child: assetImage(
                  widget.recommendGood?.pic??"",
                  width: double.infinity,
                  fit: BoxFit.fill,
                ),
              ),
            ),
            Container(
              alignment: Alignment.centerLeft,
              padding: EdgeInsets.fromLTRB(12.w, 8.h, 12.w, 0.h),
              child: Text(widget.recommendGood?.name??"",
                  style: TextStyle(color: Color(0xff2D3137), fontSize: 13.sp),
                  overflow: TextOverflow.ellipsis,
                  maxLines: 1,
                  textAlign: TextAlign.left,
                  textWidthBasis: TextWidthBasis.parent),
            ),
            GoodsTag(widget.recommendGood?.productType??-1),
            Container(
              alignment: Alignment.topLeft,
              padding: EdgeInsets.fromLTRB(12.w, 6.h, 12.w, 0),
              child: PriceInfoDealWith(
                isAskPriceFlag:widget.recommendGood?.isAskPriceFlag,
                askPriceTag:widget.recommendGood?.askPrice,
                priceText: widget.recommendGood?.price?.toString(),
                unitText: widget.recommendGood?.unit,
                saleText: widget.recommendGood?.saleStr,),
            )
          ],
        ),
      ),
    );
  }
}

//标签类型
class GoodsTag extends StatelessWidget {

  int type;

  GoodsTag(this.type);

  @override
  Widget build(BuildContext context) {
    return Container(
        alignment: Alignment.centerLeft,
        padding: EdgeInsets.fromLTRB(12.w, 6.h, 12.w, 0),
        child: setTag(type)
    );
  }
}